package com.wjb.xietong.util;  
  
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

import com.wjb.xietong.R;
  
public class UpdateManager  
{  
    /* 下载中 */  
    private static final int DOWNLOAD = 1;  
    /* 下载结束 */  
    private static final int DOWNLOAD_FINISH = 2;  
    /* 下载保存路径 */  
    private String mSavePath;  
    /* 记录进度条数量 */  
    private int progress;  
    /* 是否取消更新 */  
    private boolean cancelUpdate = false;  
  
    private Context mContext;  
    /* 更新进度条 */  
    private ProgressBar mProgress;  
    private Dialog mDownloadDialog;
    private String localVersion = null;
    private String serverVersion = null;
    private String apkDownloadPath = null;
    private String localDownloadPath = null;
  
    private Handler mHandler = new Handler()  
    {  
        public void handleMessage(Message msg)  
        {  
            switch (msg.what)  
            {  
            // 正在下载  
            case DOWNLOAD:  
                // 设置进度条位置  
                mProgress.setProgress(progress);  
                break;  
            case DOWNLOAD_FINISH:  
                // 安装文件  
                installApk();  
                break;  
            default:  
                break;  
            }  
        };  
    };  
  
    public UpdateManager(Context context, String localVersion, String serverVersion, String apkDownloadPath)  
    {  
        this.mContext = context;
        this.localVersion = localVersion;
        this.serverVersion = serverVersion;
        this.apkDownloadPath = apkDownloadPath;
        this.localDownloadPath =  "HeartBeat" + serverVersion + ".apk";
    }  
  
    /**
	 * 检测是否有新版本
	 * @return true：有 false：无
	 */
	public boolean checkVersion(){
		int result = compare(localVersion, serverVersion);
		if(result < 0){
			return true;
		}
		return false;
	}
	
	 /** 
     * 显示软件更新对话框 
     */  
    public void showNoticeDialog()  
    {  
        // 构造对话框  
        AlertDialog.Builder builder = new Builder(mContext);  
        builder.setTitle(R.string.soft_update_title);  
        builder.setMessage(R.string.soft_update_info);  
        // 更新  
        builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener()  
        {  
            @Override  
            public void onClick(DialogInterface dialog, int which)  
            {  
                dialog.dismiss();  
                // 显示下载对话框  
                showDownloadDialog();  
            }  
        });  
        // 稍后更新  
        builder.setNegativeButton(R.string.soft_update_later, new OnClickListener()  
        {  
            @Override  
            public void onClick(DialogInterface dialog, int which)  
            {  
                dialog.dismiss();  
            }  
        });  
        Dialog noticeDialog = builder.create();  
        noticeDialog.show();  
    }  
	
	
	/**
	 * 比较版本
	 * 
	 * @param version1 本地版本
	 * @param version2 服务器版本
	 * @return 【如果本地版本 > 服务器版本，返回1】【如果一样，返回0】【其它，返回-1】
	 */
	public static int compare(String version1, String version2) {
		if (version1 == null || version1.length() == 0 || version2 == null || version2.length() == 0 ){
			LogD.output("version is invalidate! version1:" + version1 + "version2:" + version2);
		}
		
		int index1 = 0;
		int index2 = 0;
		while(index1 < version1.length() && index2 < version2.length()) {
			int[] number1 = getValue(version1, index1);
			int[] number2 = getValue(version2, index2);
			
			//如果version1版本小于version2，那么version2的版本大
			if (number1[0] < number2[0]){
				return -1;
			}
			//如果version1版本大于version2，那么version2的版本大
			else if (number1[0] > number2[0])
			{
				return 1;
			}
			//如果上一个版本比较不出来大小的话，继续比较下一个
			else {
				index1 = number1[1] + 1;
				index2 = number2[1] + 1;
			}			
		}
		
		//如果version1与version2没有比较出版本的大小，并且两个版本的长度一致
		if(version1.length() == version2.length()){
			return 0;
		}
		//如果version1版本号比version版本号长
		if(version1.length() > version2.length()){ 
			return 1;
		}else{
			return -1;
		}
	}
	
	/**
	 * 截取小数点前的版本号
	 * 
	 * @param version 版本号
	 * @param index 开始位置
	 * @return 从开始位置到下一个小数点之间的版本号
	 */
	private static int[] getValue(String version, int index) {
		int[] value_index = new int[2];
		StringBuilder sb = new StringBuilder();
		while(index < version.length() && version.charAt(index) != '.') {
			sb.append(version.charAt(index));
			index++;
		}
		value_index[0] = Integer.parseInt(sb.toString());
		value_index[1] = index;
		
		return value_index;
	}

  
  
    /** 
     * 显示软件下载对话框 
     */  
    private void showDownloadDialog()  
    {  
        // 构造软件下载对话框  
        AlertDialog.Builder builder = new Builder(mContext);  
        builder.setTitle(R.string.soft_updating);  
        // 给下载对话框增加进度条  
        final LayoutInflater inflater = LayoutInflater.from(mContext);  
        View v = inflater.inflate(R.layout.softupdate_progress, null);  
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);  
        builder.setView(v);  
        // 取消更新  
        builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener()  
        {  
            @Override  
            public void onClick(DialogInterface dialog, int which)  
            {  
                dialog.dismiss();  
                // 设置取消状态  
                cancelUpdate = true;  
            }  
        });  
        mDownloadDialog = builder.create();  
        mDownloadDialog.show();  
        // 现在文件  
        downloadApk();  
    }  
  
    /** 
     * 下载apk文件 
     */  
    private void downloadApk()  
    {  
        // 启动新线程下载软件  
        new downloadApkThread().start();  
    }  
  
    /** 
     * 下载文件线程 
     *  
     * @author coolszy 
     *@date 2012-4-26 
     *@blog http://blog.92coding.com 
     */  
    private class downloadApkThread extends Thread  
    {  
        @Override  
        public void run()  
        {  
            try  
            {  
                // 判断SD卡是否存在，并且是否具有读写权限  
                if (null != apkDownloadPath && Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))  
                {  
                    // 获得存储卡的路径  
                    String sdpath = Environment.getExternalStorageDirectory() + "/";  
                    mSavePath = sdpath + "download";  
                    URL url = new URL(apkDownloadPath);  
                    // 创建连接  
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
                    conn.connect();  
                    // 获取文件大小  
                    int length = conn.getContentLength();  
                    // 创建输入流  
                    InputStream is = conn.getInputStream();  
  
                    File file = new File(mSavePath);  
                    // 判断文件目录是否存在  
                    if (!file.exists())  
                    {  
                        file.mkdir();  
                    }  
                    File apkFile = new File(mSavePath, localDownloadPath);  
                    FileOutputStream fos = new FileOutputStream(apkFile);  
                    int count = 0;  
                    // 缓存  
                    byte buf[] = new byte[1024];  
                    // 写入到文件中  
                    do  
                    {  
                        int numread = is.read(buf);  
                        count += numread;  
                        // 计算进度条位置  
                        progress = (int) (((float) count / length) * 100);  
                        // 更新进度  
                        mHandler.sendEmptyMessage(DOWNLOAD);  
                        if (numread <= 0)  
                        {  
                            // 下载完成  
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);  
                            break;  
                        }  
                        // 写入文件  
                        fos.write(buf, 0, numread);  
                    } while (!cancelUpdate);// 点击取消就停止下载.  
                    fos.close();  
                    is.close();  
                }  
            } catch (MalformedURLException e)  
            {  
                e.printStackTrace();  
            } catch (IOException e)  
            {  
                e.printStackTrace();  
            }  
            // 取消下载对话框显示  
            mDownloadDialog.dismiss();  
        }  
    };  
  
    /** 
     * 安装APK文件 
     */  
    private void installApk()  
    {  
        File apkfile = new File(mSavePath, localDownloadPath);  
        if (!apkfile.exists())  
        {  
            return;  
        }  
        // 通过Intent安装APK文件  
        Intent i = new Intent(Intent.ACTION_VIEW);  
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");  
        mContext.startActivity(i);  
    }  
}  